/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.perlak.filesearch;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Mateusz
 */
public class FileScanner {

    private List<FileSearchRequest> searchRequestList = new ArrayList<FileSearchRequest>();
    private List<FileSearchResult> results = new ArrayList<FileSearchResult>();
    private boolean searchExecuted = false;

    public FileScanner(List<FileSearchRequest> requests) {
        this.searchRequestList = requests;
    }

    public void search() {
        for (FileSearchRequest request : getSearchRequestList()) {
            FileSearchResult result = search(request);
            getResults().add(result);
        }
        searchExecuted = true;
    }

    private FileSearchResult search(FileSearchRequest request) {
        File rootFile = new File(request.getFullDirPath());
        FileSearchResult result = searchReg(request, rootFile.listFiles(request.getFileFilter()), null);
        return result;
    }

    private FileSearchResult searchReg(FileSearchRequest request, File[] files, FileSearchResult result) {
        if (result == null) {
            result = new FileSearchResult();
        }
        if (files == null) {
            return result;
        }
        for (File file : files) {
            if (file.isDirectory()) {// search sub folders
                searchReg(request, file.listFiles(request.getFileFilter()), result);
            } else {
                SingleFileResult fileResult = new SingleFileResult(request.getSource(), file);
                result.getFiles().add(fileResult);
            }
        }
        return result;
    }

    /**
     * @return the searchRequestList
     */
    public List<FileSearchRequest> getSearchRequestList() {
        if (!searchExecuted) {
            search();
        }
        return searchRequestList;
    }

    /**
     * @return the results
     */
    public List<FileSearchResult> getResults() {
        return results;
    }

    /**
     * @param results the results to set
     */
    public void setResults(List<FileSearchResult> results) {
        this.results = results;
    }

    /**
     * @return the searchExecuted
     */
    public boolean isSearchExecuted() {
        return searchExecuted;
    }
}
